from flask import Blueprint, jsonify, request
from app.services.user_service import UserService

bp = Blueprint('user_routes', __name__)
user_service = UserService()

@bp.route('/user', methods=['POST'])
def create_user():
    """
    创建用户，并初始化用户的 `user_factor` 数据。
    """
    data = request.get_json()
    if not data:
        return jsonify({"message": "Invalid data"}), 400

    try:
        new_user = user_service.create_user(data)
        return jsonify({
            "message": "User created successfully",
            "user_id": new_user.user_id
        }), 201
    except Exception as e:
        return jsonify({"message": str(e)}), 500


@bp.route('/wxlogin', methods=['POST'])
def wx_login():
    """处理微信登录请求"""
    code = request.json.get('code')
    if not code:
        return jsonify({'error': 'Code is required'}), 400

    try:
        user, session_key = user_service.wx_login(code)
        return jsonify({
            'openid': user.openid,
            'session_key': session_key,
            'user_id': user.user_id,
            'phone': user.phone,
            'gender': user.gender,
            'birthday': user.birthday,
            'province': user.province,
            'city': user.city,
            'district': user.district,
        })
    except ValueError as e:
        return jsonify({'error': str(e)}), 400


@bp.route('/userInfo', methods=['POST'])
def user_info():
    try:
        # 获取请求中的用户信息
        data = request.get_json()
        user_info = data.get('userInfo')

        # 调用 UserService 类来更新用户信息
        user_service = UserService()
        result = user_service.update_user_info(user_info)

        return jsonify(result)

    except Exception as e:
        return jsonify({"success": False, "message": f"请求处理失败: {str(e)}"}), 400



@bp.route('/<user_id>', methods=['GET'])
def get_user(user_id):
    body_info, error = user_service.get_user_body_info(user_id)
    if error:
        return jsonify({"message": error}), 404
    # 返回用户身体信息
    return jsonify(body_info)


# 更新用户身体信息
@bp.route('/<user_id>/bodyInfo', methods=['PUT'])
def update_user_body_info(user_id):
    try:
        # 获取请求的JSON数据
        data = request.get_json()

        # 更新用户信息
        body_info, error = user_service.get_user_body_info(user_id)
        if error:
            return jsonify({"message": error}), 404
        # 调用服务层方法来更新用户身体数据
        updated_body_info, error = user_service.update_user_body_info(user_id, data)
        if error:
            return jsonify({"message": error}), 400
        return jsonify({"message": "User body info updated successfully", "body_info": updated_body_info}), 200
    except Exception as e:
        return jsonify({"message": str(e)}), 500

# 路由：获取用户的实际营养推荐摄入量
@bp.route('/nutrition/recommendation', methods=['GET'])
def get_nutrition_recommendation():
    user_id = request.args.get('user_id')
    nutrient_id = request.args.get('nutrient_id', type=int)

    if not user_id or not nutrient_id:
        return jsonify({"error": "user_id and nutrient_id are required"}), 400

    try:
        actual_recommendation = user_service.get_actual_recommendation(user_id, nutrient_id)
        if actual_recommendation is None:
            return jsonify({"error": "Nutrient not found"}), 404

        return jsonify({
            "user_id": user_id,
            "nutrient_id": nutrient_id,
            "actual_recommendation": actual_recommendation
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500